package com.weiqiao.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CarouseEntity;
import com.weiqiao.mall.domain.CommodityEntity;
import com.weiqiao.mall.repository.ISlideshowRepository;
import com.weiqiao.mall.service.dto.VarietyDTO;
import com.weiqiao.mall.domain.VarietyEntity;
import com.weiqiao.mall.repository.ICommodityRepository;
import com.weiqiao.mall.repository.IVarietyRepository;
import com.weiqiao.mall.service.IVarietyService;
import com.weiqiao.mall.service.vo.CascadeVO;
import com.weiqiao.mall.service.vo.CommodityTypeVO;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.PageUtil;
import com.weiqiao.utils.SecurityUtils;
import com.weiqiao.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author PENGLIWEI
 * @createDate 2019-10-25
 */
@Log4j
@Service("VarietyServiceImpl")
public class VarietyServiceImpl implements IVarietyService {

    @Autowired
    @Qualifier("VarietyRepositoryImpl")
    private IVarietyRepository varietyRepository;

    /**
     * 商品管理数据层
     */
    @Autowired
    private ICommodityRepository commodityRepository;

    @Autowired
    private ISlideshowRepository slideshowRepository;

    @Override
    public List<VarietyEntity> selectList(Document doc, Pageable pageable) {
        Gson gson = new Gson();
        List<VarietyEntity> varietylist = new ArrayList<>();
        List<String> list = varietyRepository.selectList(doc, pageable);
        if (!list.isEmpty()) {
            for (String a : list) {
                VarietyEntity varietyEntity = gson.fromJson(a, VarietyEntity.class);
                varietyEntity.setCreate_time(DateFormatUtils.format(Long.parseLong(varietyEntity.getCreate_time()), "yyyy-MM-dd HH:mm"));
                varietylist.add(varietyEntity);
            }
        }
        return varietylist;
    }


    public List<VarietyDTO> getListDTO(Document doc, Bson sort) {
        Gson gson = new Gson();
        List<VarietyDTO> varietyList = new ArrayList<>();
        List<String> list = varietyRepository.getVarietyListBySort(doc, sort);
        if (!list.isEmpty()) {
            for (String a : list) {
                VarietyDTO varietyEntity = gson.fromJson(a, VarietyDTO.class);
                varietyList.add(varietyEntity);
            }
        }
        return varietyList;
    }

    @Override
    public Map getList(CommodityTypeVO commodityTypeVO) {
        Document doc = new Document();
        doc.append("company_id", commodityTypeVO.getCompany_id());
        doc.append("is_delete", 0);
        //查询总记录数
        int total = this.getOrderLogCount(commodityTypeVO.getCompany_id(), doc);
        //一级分类数
        Document sort = new Document();
        sort.append("sort", 1);
        List<VarietyDTO> list = this.getListDTO(doc, sort);
        Document slide_doc = new Document("company_id", commodityTypeVO.getCompany_id());
        slide_doc.append("delete_flag", 0);
        List<String> carouseStrList = slideshowRepository.getCarouseList(slide_doc);
        Gson gson = new Gson();
        Map<String, String> carouseUrlMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(carouseStrList)) {
            for (String str : carouseStrList) {
                CarouseEntity carouseEntity = gson.fromJson(str, CarouseEntity.class);
                carouseUrlMap.put(carouseEntity.getCarouse_id(), (CollectionUtils.isNotEmpty(carouseEntity.getCarouseList()) ?
                        carouseEntity.getCarouseList().get(0).getUrl() : ""));
            }
        }
        //把二级分类包装在一级分类的children中
        if (CollectionUtils.isNotEmpty(list)) {
            for (VarietyDTO varietyEntity : list) {
                List<VarietyDTO> list_children = new ArrayList<>();
                varietyEntity.setParent_id("0");
                varietyEntity.setCarouse_img((carouseUrlMap.get(varietyEntity.getCarouse_id()) == null ? ""
                        : carouseUrlMap.get(varietyEntity.getCarouse_id())));
                List<VarietyEntity.SecondVariety> secondVarietyList = varietyEntity.getSecondVarietyList();
                for (VarietyEntity.SecondVariety secondVariety : secondVarietyList) {
                    VarietyDTO varietyDTO = new VarietyDTO();
                    varietyDTO.setVariety_id(secondVariety.getSecond_variety_id());
                    varietyDTO.setVariety_name(secondVariety.getSecond_variety_name());
                    varietyDTO.setIcon_url(secondVariety.getSecond_variety_img());
                    varietyDTO.setCompany_id(secondVariety.getCompany_id());
                    varietyDTO.setCreate_time(secondVariety.getCreate_time());
                    varietyDTO.setParent_id(varietyEntity.getVariety_id());
                    varietyDTO.setCarouse_id(secondVariety.getSecond_variety_carouse_id());
                    varietyDTO.setCarouse_img(carouseUrlMap.get(secondVariety.getSecond_variety_carouse_id()) == null ? ""
                            : carouseUrlMap.get(secondVariety.getSecond_variety_carouse_id()));
                    list_children.add(varietyDTO);
                }
                varietyEntity.setChildren(list_children);
            }
        } else {
            // 当没有数据时造一条空数据
            String currentTime = String.valueOf(System.currentTimeMillis());
            VarietyDTO varietyDTO = new VarietyDTO();
            varietyDTO.setVariety_id(currentTime);
            varietyDTO.setVariety_name("");
            varietyDTO.setParent_id("0");
            varietyDTO.setIcon_url("");
            list.add(varietyDTO);
        }
        return PageUtil.toPage(list, total);
    }

    @Override
    public List<VarietyEntity> selectCompanyList(int company_id) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("is_delete", 0);
        Bson filter = Filters.and(filter1, filter2);
        Bson sort = Filters.eq("sort", 1);
        List<String> list = varietyRepository.getVarietyListBySort(filter, sort);
        return this.getVarietyListString(list);
    }

    private List<VarietyEntity> getVarietyListString(List<String> list) {
        List<VarietyEntity> varietyList = new ArrayList<>();
        if (!list.isEmpty()) {
            Gson gson = new Gson();
            for (String a : list) {
                VarietyEntity varietyEntity = gson.fromJson(a, VarietyEntity.class);
                varietyList.add(varietyEntity);
            }
        }
        return varietyList;
    }

    @Override
    public List<VarietyEntity> selectCompanyList(int company_id, int is_home) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("is_delete", 0);
        Bson filter3 = Filters.eq("is_home", is_home);
        Bson filter = Filters.and(filter1, filter2, filter3);
        List<String> list = varietyRepository.selectCompanyList(filter);
        return this.getVarietyListString(list);
    }

    @Override
    public boolean saveVariety(VarietyEntity varietyEntity) {
        String json = new Gson().toJson(varietyEntity);
        return varietyRepository.saveVariety(json);
    }

    @Override
    public int getOrderLogCount(int company_id, Document doc) {
        return varietyRepository.getOrderLogCount(company_id, doc);
    }

    @Override
    public boolean deleteById(int company_id, String variety_id) {
        Bson filter1 = Filters.eq("company_id", company_id);
        Bson filter2 = Filters.eq("variety_id", variety_id);
        Bson filter = Filters.and(filter1, filter2);
        Document doc = new Document();
        doc.append("is_delete", 1);
        return varietyRepository.deleteById(filter, doc, false);
    }

    @Override
    public VarietyEntity findVarietyById(String variety_id) {
        String s = varietyRepository.findVarietyFilter(Filters.eq("variety_id", variety_id));
        VarietyEntity entity;
        if (!StringUtils.isBlank(s)) {
            entity = new Gson().fromJson(s, VarietyEntity.class);
        } else {
            entity = new VarietyEntity();
        }
        return entity;
    }

    @Override
    public VarietyEntity getVarietyById(Bson filter) {
        String s = varietyRepository.findVarietyFilter(filter);
        VarietyEntity entity = null;
        if (StringUtils.isNotBlank(s)) {
            entity = new Gson().fromJson(s, VarietyEntity.class);
        }
        return entity;
    }

    @Override
    public boolean updateVariety(Bson filter, Document doc) {
        return varietyRepository.updateVariety(filter, doc, false);
    }

    /**
     * 获取宝贝分类 tree
     *
     * @param request
     * @return
     */
    @Override
    public Map getVarietyTreeList(HttpServletRequest request) {
        //组装前端传递的排序规则
        String sortRule = request.getParameter("sort");
        String sort = "create_time";
        String ascOrDesc = "ASC";
        if (StringUtils.isNotBlank(sortRule)) {
            String[] rule = sortRule.split(",");
            sort = rule[0];
            ascOrDesc = rule[1].toUpperCase();
        }
        Integer index = "ASC".equals(ascOrDesc) ? 1 : -1;
        Integer companyId = MallUtil.getCompanyId(request);
        //拼接查询条件
        Bson filter = Filters.and(Filters.eq("company_id", companyId), Filters.eq("is_delete", 0));
        Bson sortFilter = Filters.eq(sort, index);
        List<String> stringList = varietyRepository.getVarietyListBySort(filter, sortFilter);
        List<Map> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(stringList)) {
            Gson gson = new Gson();
            for (String str : stringList) {
                VarietyEntity varietyEntity = gson.fromJson(str, VarietyEntity.class);
                Map map = new HashMap(4);
                map.put("label", varietyEntity.getVariety_name());
                map.put("path_name", varietyEntity.getVariety_name());
                map.put("variety_id", varietyEntity.getVariety_id());
                List<VarietyEntity.SecondVariety> secondVarietyList = varietyEntity.getSecondVarietyList();
                List<Map> secondList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(secondVarietyList)) {
                    for (VarietyEntity.SecondVariety secondVariety : secondVarietyList) {
                        Map secondMap = new HashMap(3);
                        secondMap.put("label", secondVariety.getSecond_variety_name());
                        secondMap.put("path_name", varietyEntity.getVariety_name() + ">>"
                                + secondVariety.getSecond_variety_name());
                        secondMap.put("variety_id", secondVariety.getSecond_variety_id());
                        secondList.add(secondMap);
                    }
                }
                if (CollectionUtils.isNotEmpty(secondList)) {
                    map.put("children", secondList);
                }
                resultList.add(map);
            }
        }
        Map resultMap = new HashMap(1);
        resultMap.put("content", resultList);
        return resultMap;
    }

    @Override
    public Map saveVarietyList(CommodityTypeVO commodityTypeVO) {
        String varietyJsonStr = commodityTypeVO.getVarietyData();
        // 先获取删除的id，保存之前先删除数据
        String[] split = commodityTypeVO.getVarietyIds();
        Map resultMap = new HashMap();
        if (StringUtils.isBlank(varietyJsonStr)) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有数据需要保存");
            return resultMap;
        }
        int company_id = commodityTypeVO.getCompany_id();
        List<Map<String, Object>> varietyList = JSONArray.parseObject(varietyJsonStr, List.class);
        if (CollectionUtils.isEmpty(varietyList)) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有数据需要保存");
            return resultMap;
        }
        try {
            //把前端删除的一级分类逻辑删除
            if (!"".equals(split) && split.length > 0) {
                for (String vatietyId : split) {
                    // 执行删除商品分类逻辑删除
                    Document doc = new Document("company_id", company_id).append("is_delete", 0)
                            .append("variety_id", vatietyId);
                    varietyRepository.updateVariety(doc, new Document("is_delete", 1), false);
                }
            }
            //排序字段
            int sort = 0;
            //循环取出一级分类
            for (Map map : varietyList) {
                String variety_id = MapUtils.getString(map, "variety_id", "");
                String variety_name = MapUtils.getString(map, "variety_name", "");
                //判断分类id和分类名称是否为空,若都为空，则不保存
                if (StringUtils.isBlank(variety_id) || StringUtils.isBlank(variety_name)) {
                    continue;
                }
                Document varietyDoc = new Document();
                varietyDoc.append("variety_id", variety_id);
                varietyDoc.append("company_id", company_id);
                varietyDoc.append("is_delete", 0);
                String jsonStr = varietyRepository.findVarietyFilter(varietyDoc);
                boolean bool = false;
                String old_variety_name = "";
                if (StringUtils.isBlank(jsonStr)) {
                    //新增
                    bool = true;
                } else {
                    VarietyEntity varietyEntity = new Gson().fromJson(jsonStr, VarietyEntity.class);
                    old_variety_name = varietyEntity.getVariety_name();
                }
                String variety_code = MapUtils.getString(map, "variety_code", "");
                int create_by = MapUtils.getIntValue(map, "create_by", 0);
                String create_time = MapUtils.getString(map, "create_time", "");
                String carouse_id = MapUtils.getString(map, "carouse_id", "");
                String icon_url = MapUtils.getString(map, "icon_url", "");
                int is_home = MapUtils.getIntValue(map, "is_home", 0);
                List<Map<String, Object>> childrenListMap = new ArrayList<>();
                Object children = map.get("children");
                if (children != null || children instanceof List) {
                    List<Map<String, Object>> childrenList = (List<Map<String, Object>>) children;
                    if (CollectionUtils.isNotEmpty(childrenList)) {
                        for (Map<String, Object> stringMap : childrenList) {
                            Map<String, Object> m = new HashMap<>();
                            String second_variety_id = MapUtils.getString(stringMap, "variety_id", "");
                            String second_variety_name = MapUtils.getString(stringMap, "variety_name", "");
                            String second_variety_carouse_id = MapUtils.getString(stringMap, "carouse_id", "");
                            if (StringUtils.isBlank(second_variety_id) || StringUtils.isBlank(second_variety_name)) {
                                continue;
                            }
                            // 判断是否是新增的二级分类
                            if (StringUtils.isBlank(MapUtils.getString(stringMap, "create_time", ""))) {
                                m.put("second_variety_id", String.valueOf(System.currentTimeMillis()));
                            } else {
                                m.put("second_variety_id", second_variety_id);
                            }
                            String time = MapUtils.getString(stringMap, "create_time", "");
                            if (StringUtils.isBlank(time)) {
                                time = String.valueOf(System.currentTimeMillis());
                            }
                            m.put("second_variety_id", second_variety_id);
                            m.put("second_variety_name", second_variety_name);
                            m.put("sort", 0);
                            m.put("second_variety_img", MapUtils.getString(stringMap, "icon_url", ""));
                            m.put("companay_id", company_id);
                            m.put("create_time", time);
                            m.put("second_variety_carouse_id", second_variety_carouse_id);
                            childrenListMap.add(m);
                        }
                    }
                }
                Document document = new Document();
                if (bool) {
                    //新增
                    document.append("variety_id", String.valueOf(System.currentTimeMillis()));
                    document.append("variety_code", variety_code);
                    document.append("variety_name", variety_name);
                    document.append("create_by", SecurityUtils.getUserId().intValue());
                    document.append("create_time", String.valueOf(System.currentTimeMillis()));
                    document.append("company_id", company_id);
                    document.append("is_delete", 0);
                    document.append("is_home", 1);
                } else {
                    //修改
                    document.append("variety_code", variety_code);
                    document.append("variety_name", variety_name);
                    document.append("create_by", create_by);
                    document.append("create_time", create_time);
                    document.append("company_id", company_id);
                    document.append("is_delete", 0);
                    document.append("is_home", is_home);
                    //判断是否修改了分类名称,若修改了，则需要修改商品关联的分类名称
                    if (!old_variety_name.equals(variety_name)) {
                        Document doc_variety = new Document("company_id", company_id).append("variety_id", variety_id);
                        List<CommodityEntity> commodityList = new ArrayList<>();
                        List<String> list = commodityRepository.findCommoditys(company_id, doc_variety);
                        if (CollectionUtils.isNotEmpty(list)) {
                            list.forEach(commodity -> commodityList.add(new Gson().fromJson(commodity,
                                    CommodityEntity.class)));
                        }
                        if (CollectionUtils.isNotEmpty(commodityList)) {
                            for (CommodityEntity commodityEntity : commodityList) {
                                Document doc_commodityId = new Document("company_id", company_id)
                                        .append("commodity_id", commodityEntity.getCommodity_id());
                                commodityRepository.updateOneCommodity(company_id, doc_commodityId,
                                        new Document("variety_name", variety_name), false);
                            }
                        }
                    }
                }
                document.append("carouse_id", carouse_id);
                document.append("icon_url", icon_url);
                document.append("sort", sort++);
                document.append("secondVarietyList", childrenListMap);
                //新增时 bool为true，修改时bool为false
                varietyRepository.updateVariety(varietyDoc, document, bool);
            }
            resultMap.put("result", true);
            resultMap.put("msg", "保存成功");
            return resultMap;
        } catch (Exception e) {
            log.error("保存宝贝标签失败");
            e.printStackTrace();
            resultMap.put("result", false);
            resultMap.put("msg", "保存失败");
            return resultMap;
        }
    }

    @Override
    public List<CascadeVO> selectSecondVarietyList(int company_id) {
        //获取商品所有分类（包含一级和二级分类）
        List<VarietyEntity> varietyList = this.selectCompanyList(company_id);
        // 封装的级联选择器实体类
        List<CascadeVO> list = new ArrayList<>();
        for (VarietyEntity entity : varietyList) {
            CascadeVO info = new CascadeVO();
            info.setValue(entity.getVariety_id());
            info.setLabel(entity.getVariety_name());
            // 二级分类不为空
            if (CollectionUtils.isNotEmpty(entity.getSecondVarietyList())) {
                List<CascadeVO.CascadeChildrenVo> childrenVoList = new ArrayList<>();
                for (VarietyEntity.SecondVariety pojo : entity.getSecondVarietyList()) {
                    CascadeVO.CascadeChildrenVo children = new CascadeVO.CascadeChildrenVo();
                    children.setValue(pojo.getSecond_variety_id());
                    children.setLabel(pojo.getSecond_variety_name());
                    childrenVoList.add(children);
                }
                info.setChildren(childrenVoList);
            }
            list.add(info);
        }
        return list;
    }
}
